package com.zhengxin.one.utils;

import cn.hutool.crypto.SecureUtil;
import com.zhengxin.one.entity.client.SignRule;
import org.apache.commons.lang.StringUtils;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public  class SignUtil {

    public static  List<SignRule> getRules(List<String> signFields,Class clazz){
        List<SignRule> rules = new ArrayList<>();
        Field[] fields = clazz.getDeclaredFields();
        for(Field field:fields){
            SignRule rule = new SignRule();
            rule.setFieldName(field.getName());
            if(signFields.contains(field.getName())){
                rule.setIsSign(1);
            }
            rules.add(rule);
        }
        return rules;
    }

    public  static <T> String  generateSign(List<String> signFields,String appKey,T t) throws Exception {
        List<SignRule> rules = getRules(signFields, t.getClass());
        Collections.sort(rules);
        StringBuilder signBuilder = new StringBuilder();
        for (SignRule rule : rules) {
            if(rule.getIsSign()==0){continue;}

            String fieldName = rule.getFieldName();
            Method method = t.getClass().getMethod("get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1), new Class[]{});
            Object invoke = method.invoke(t);
            if (invoke != null && StringUtils.isNotBlank(invoke.toString())) {
                if (signBuilder.length() == 0) {
                    signBuilder.append(fieldName + "=" + invoke.toString());
                } else {
                    signBuilder.append("&" + fieldName + "=" + invoke.toString());
                }

            }
        }
        return SecureUtil.md5(signBuilder.toString()+"&appkey="+appKey).toLowerCase();
    }


}
